#pragma once
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include "log.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include "ThreadPool.hpp"
#include "Task.hpp"

namespace server
{

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };
    class tcpServer
    {
        // static const uint16_t dport = 20000;
        static const uint16_t defport;
        static const int gbacklog = 20;

    public:
        tcpServer(const uint16_t port = defport) : _sock(-1), _port(port)
        {
        }
        ~tcpServer()
        {
            if(_sock > 0) close(_sock);
        }

        void initServer()
        {
            // 创建套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                logcout(FATAL, "create socket error !!");
                exit(SOCKET_ERR);
            }
            logcout(NORMAL, "create socket error !!");

            // 绑定bind
            struct sockaddr_in addr;
            addr.sin_port = htons(_port);
            addr.sin_family = AF_INET;
            // addr.sin_family= PF_INET;  一样的

            addr.sin_addr.s_addr = inet_addr("0.0.0.0");
            addr.sin_addr.s_addr = INADDR_ANY;

            int ret = bind(_sock, (struct sockaddr *)&addr, sizeof(addr));
            if (ret < 0)
            {
                logcout(FATAL, "bind socket error!!");
                exit(BIND_ERR);
            }
            logcout(NORMAL, "bind socket success!!");

            // 设置监听状态

            ret = listen(_sock, gbacklog);
            if (ret < 0)
            {
                logcout(FATAL, "listen socket error!!");
                exit(LISTEN_ERR);
            }
            logcout(NORMAL, "listen socket success!!");
        }

        void start()
        {
            for (;;)
            {
                struct sockaddr_in caddr;
                socklen_t len = sizeof(caddr); // 这里是 值-结果参数
                int newsock = accept(_sock, (struct sockaddr *)&caddr, &len);
                // 返回一个新的文件描符号 用于通信
                if (newsock < 0)
                {
                    logcout(ERROR, "accept a new link error!!");
                    continue;
                }
                logcout(NORMAL, "accept a new link success!!");
                std::cout << "accept sock : " << newsock << std::endl;
                // serverIo(newsock);
                // close(newsock);

                ThreadPool<Task>::getInstance()->push(Task(newsock, serviceIO));
            }
        }

    private:
        int _sock; // 不是用来通信的是用来监听链接的
        uint16_t _port;
    };
    const uint16_t tcpServer::defport = 20000;

}
